const express = require("express");
const router = express.Router();
const path = require("path");
const multer = require("multer");
const upload = multer({ dest: path.join(__dirname, "../../../public/images") });

const { timeTrans } = require("../../../utils");
const {
  getTool,
  addTool,
  updateTool,
  deleteTool,
} = require("../../../model/weixin/admin/tool.js");

/* Tool增删改查 */

// 查找Tool
router.get("/", async function (req, res, next) {
  let data = await getTool();
  res.send(data);
});

// 添加Tool图片
router.post("/add", upload.single("banner"), (req, res, next) => {
  const title = req.body.title;
  const src = "http://localhost:3333/images/" + req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  addTool([title, src, atime])
    .then(() => {
      res.send({
        code: 200,
        msg: "添加成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "添加失败",
        err,
      });
    });
});

// 修改Tool图片
router.post("/update", (req, res, next) => {
  console.log(req.body);
  const id = Number(req.body.id);
  const title = req.body.title;
  const src =
    "http://localhost:3333/images/" + req.body["src[name]"] ||
    req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  updateTool([title, src, atime, id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改轮播图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改轮播图片失败",
        err,
      });
    });
});

// 删除单个Tool图片
router.get("/delete", (req, res, next) => {
  const id = Number(req.query.id);
  deleteTool([id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除图片失败",
      });
    });
});

module.exports = router;
